package fiscal.gui.classificacao;

import java.awt.Toolkit;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;

import load.properties.Mensagem;
import message.erro.IdMessage;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;

import exceptions.PersistenceExceptionMessage;
import fiscal.action.ClassificacaoActionsManager;
import fiscal.entities.tables.Classificacao;
import generic.gui.util.FixedLengthDocument;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.border.BevelBorder;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;

@SuppressWarnings("serial")
public class ClassificacaoCadastro extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JButton btnSalvar;
	private JButton btnAlterar;
	private JButton btnSair;
	private JTextField textFieldDesc;
	private JTextField textFieldClassif;
	
	private ClassificacaoActionsManager action;
	private Classificacao classificacao;
	private ArrayList<Classificacao> classificacaos;
	private ArrayList<Classificacao> classificacaoFilhosAtualizados;
	private JLabel label;
	private JScrollPane scrollPane;
	private JTextArea textArea;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			new ClassificacaoCadastro();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public ClassificacaoCadastro() {
		setTitle("Cadastro de Classifica\u00E7\u00E3o Fiscal");
		try {
			setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			setBounds(100, 100, 470, 341);
			setResizable(false);
			setLocationRelativeTo(null);
			setModal(true);
			getContentPane().setLayout(null);
			contentPanel.setBounds(0, 0, 464, 309);
			
			contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
			getContentPane().add(contentPanel);
			JLabel lblClassificao = new JLabel("Classifica\u00E7\u00E3o");
			lblClassificao.setBounds(22, 11, 96, 14);
			JLabel lblDescrio = new JLabel("Descri\u00E7\u00E3o");
			lblDescrio.setBounds(124, 11, 130, 14);
			contentPanel.setLayout(null);
			contentPanel.add(getBtnSalvar());
			contentPanel.add(getBtnSair());
			contentPanel.add(lblClassificao);
			contentPanel.add(getTextFieldClassif());
			contentPanel.add(lblDescrio);
			contentPanel.add(getTextFieldDesc());
			contentPanel.add(getLabel());
			contentPanel.add(getScrollPane_1());
			contentPanel.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{getTextFieldClassif(), getTextFieldDesc(), getScrollPane_1(), getBtnSalvar(), getBtnSair()}));
			setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public ClassificacaoCadastro(Classificacao classificacao) {
		setTitle("Altera\u00E7\u00E3o de Classifica\u00E7\u00E3o Fiscal");
		setClassificacao(classificacao);
		getTextFieldClassif().setEditable(false);
		getTextFieldClassif().setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
		try {
			setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			setBounds(100, 100, 470, 341);
			setResizable(false);
			setLocationRelativeTo(null);
			setModal(true);
			getContentPane().setLayout(null);
			contentPanel.setBounds(0, 0, 464, 309);
			
			contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
			getContentPane().add(contentPanel);
			JLabel lblClassificao = new JLabel("Classifica\u00E7\u00E3o");
			lblClassificao.setBounds(22, 11, 96, 14);
			JLabel lblDescrio = new JLabel("Descri\u00E7\u00E3o");
			lblDescrio.setBounds(124, 11, 130, 14);
			contentPanel.setLayout(null);
			contentPanel.add(getBtnAlterar());
			contentPanel.add(getBtnSair());
			contentPanel.add(lblClassificao);
			contentPanel.add(getTextFieldClassif());
			contentPanel.add(lblDescrio);
			contentPanel.add(getTextFieldDesc());
			contentPanel.add(getLabel());
			contentPanel.add(getScrollPane_1());
			contentPanel.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{getTextFieldClassif(), getTextFieldDesc(), getScrollPane_1(), getBtnSalvar(), getBtnSair()}));
	
			setFormFull(getClassificacao());
			getTextFieldClassif().setFocusable(false);
			
			setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void setFormFull(Classificacao classificacao) {
		if (classificacao != null) {
			getTextFieldClassif().setText(classificacao.getId());
			setFormMenosClassificacao(classificacao);
		}
	}

	private JButton getBtnSalvar() {
		if (btnSalvar == null) {
			btnSalvar = new JButton("Salvar");
			btnSalvar.setBounds(152, 264, 73, 23);
			btnSalvar.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == 40) {
						getBtnSair().requestFocus();
					}
					if (e.getKeyCode() == 38) {
						getTextArea().requestFocus();
					}
				}
			});
			btnSalvar.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					Classificacao classificacao = getInstanceEntityForm();
					
					try {
						IdMessage erro = getAction().validEntityPersist(classificacao);
						if (erro != null) 
							notificaErroSetCampo(erro);
						else {
							classificacao.persist();
							
							ArrayList<Classificacao> filhos = getAction().findChildrens(classificacao.getPai());
							
							for (Classificacao filho : filhos) {
								if (!filho.equals(classificacao)) {
									if (classificacao.equals(filho.findPai())) {
										filho.setPai(classificacao);
										filho.merge();
										getClassificacaoFilhosAtualizados().add(filho);
									}
								}
							}
							getClassificacaos().add(classificacao.find(classificacao.getId()));
							clearFormFull();
							getTextFieldClassif().grabFocus();
						}
					} catch (PersistenceExceptionMessage exc) {
						// TODO Auto-generated catch block
						exc.printStackTrace();
					}
				}

				
			});
		}
		return btnSalvar;
	}
	public JButton getBtnAlterar() {
		if (btnAlterar == null) {
			btnAlterar = new JButton("Alterar");
			btnAlterar.setBounds(152, 264, 73, 23);
			btnAlterar.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					Classificacao classificacao = getInstanceEntityForm();
					classificacao.setId(getClassificacao().getId());
					try {
						IdMessage erro = getAction().validEntityAlter(classificacao);
						if (erro != null)
							notificaErroSetCampo(erro);
						else {
							classificacao.merge();
							getClassificacaos().add(classificacao);
							dispose();
						}
					} catch (PersistenceExceptionMessage exc) {
						// TODO Auto-generated catch block
						exc.printStackTrace();
					}
				}
			});
			btnAlterar.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == 40) {
						getBtnSair().requestFocus();
					}
					if (e.getKeyCode() == 38) {
						getTextArea().requestFocus();
					}
				}
			});
		}
		return btnAlterar;
	}

	public void setBtnAlterar(JButton btnAlterar) {
		this.btnAlterar = btnAlterar;
	}

	private void clearFormFull() {
		getTextFieldClassif().setText("");
		clearFormMenosClassificacao();
	}
	private void clearFormMenosClassificacao() {
		getTextFieldDesc().setText("");
		
		getTextArea().setText("");
	}

	public ArrayList<Classificacao> getClassificacaoFilhosAtualizados() {
		if (classificacaoFilhosAtualizados == null) {
			classificacaoFilhosAtualizados = new ArrayList<Classificacao>();
		}
		return classificacaoFilhosAtualizados;
	}
	private void notificaErroSetCampo(IdMessage erro) {
		if (erro != null) {
			Toolkit.getDefaultToolkit().beep();
			JOptionPane.showMessageDialog(null, erro.toString(), Mensagem.getValue(Mensagem.TITULO_DIALOGO_ALERTA), JOptionPane.WARNING_MESSAGE);
			setFocusCampo(erro.getId());
		}
	}
	private void notificaErro(IdMessage erro) {
		if (erro != null) {
			Toolkit.getDefaultToolkit().beep();
			JOptionPane.showMessageDialog(null, erro.toString(), Mensagem.getValue(Mensagem.TITULO_DIALOGO_ALERTA), JOptionPane.WARNING_MESSAGE);
		}
	}
	
	private void setFocusCampo(Integer index) {
		if (index != null) {
			switch (index) {
				case 1:
					getTextFieldClassif().grabFocus();
					break;
				case 2:
					getTextFieldDesc().grabFocus();
					break;
				case 3:
					getTextArea().grabFocus();
					break;
			}
		}
	}

	private Classificacao getInstanceEntityForm() {
		Classificacao classificacao = new Classificacao();
		classificacao.setId(getTextFieldClassif().getText());
		classificacao.setProdutoEnquadrado(getTextArea().getText());
		classificacao.setDescricao(getTextFieldDesc().getText().trim());
		try {
			classificacao.setPai(getAction().getPaiClassificacao(classificacao));
		} catch (PersistenceExceptionMessage e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		return classificacao;
	}
	private JButton getBtnSair() {
		if (btnSair == null) {
			btnSair = new JButton("Sair");
			btnSair.setBounds(229, 264, 75, 23);
			btnSair.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == 40) {
						if (!getTextFieldClassif().isFocusable())
							getTextFieldDesc().requestFocus();
						else
							getTextFieldClassif().requestFocus();
					}
					if (e.getKeyCode() == 38) {
						if (btnAlterar != null)
							getBtnAlterar().requestFocus();
						else
							getBtnSalvar().requestFocus();
					}
				}
			});
			btnSair.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					dispose();
				}
			});
		}
		return btnSair;
	}
	private JTextField getTextFieldDesc() {
		if (textFieldDesc == null) {
			textFieldDesc = new JTextField();
			textFieldDesc.setBounds(124, 25, 316, 22);
			textFieldDesc.setDocument(new FixedLengthDocument(61));
			textFieldDesc.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.getKeyChar() == KeyEvent.VK_ENTER || arg0.getKeyCode() == 40) {
						getTextArea().requestFocus();
					}
					if (arg0.getKeyCode() == 38) {
						getTextFieldClassif().requestFocus();
					}
				}
			});
			textFieldDesc.setColumns(10);
		}
		return textFieldDesc;
	}
	private JTextField getTextFieldClassif() {
		if (textFieldClassif == null) {
			textFieldClassif = new JTextField();
			textFieldClassif.setBounds(22, 25, 96, 22);
			textFieldClassif.addFocusListener(new FocusAdapter() {
				@Override
				public void focusLost(FocusEvent arg0) {
					try {
						if (getClassificacao() == null && arg0.getOppositeComponent() != null && !getBtnSair().equals(arg0.getOppositeComponent()))
							notificaErro(getAction().eValidoIdClassificacaoForPersiste(getInstanceEntityForm()));
					} catch (PersistenceExceptionMessage e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
			textFieldClassif.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent arg0) {
					try {

						if (getTextFieldClassif().getText().trim().length() == 4)
							setFormMenosClassificacao(getAction().findEntityFromForm(getTextFieldClassif().getText().trim()));
						if (getTextFieldClassif().getText().trim().length() == 5) 
							setFormMenosClassificacao(getAction().findEntityFromForm(getTextFieldClassif().getText().trim()));
						if (getTextFieldClassif().getText().trim().length() == 6) 
							setFormMenosClassificacao(getAction().findEntityFromForm(getTextFieldClassif().getText().trim()));
						if (getTextFieldClassif().getText().trim().length() == 7) 
							setFormMenosClassificacao(getAction().findEntityFromForm(getTextFieldClassif().getText().trim()));
						if (getTextFieldClassif().getText().trim().length() == 8)
							setFormMenosClassificacao(getAction().findEntityFromForm(getTextFieldClassif().getText().trim()));
					} catch (PersistenceExceptionMessage e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.getKeyChar() == KeyEvent.VK_ENTER || arg0.getKeyCode() == 40) {
						getTextFieldDesc().requestFocus();
					}
				}
			});
			textFieldClassif.setColumns(10);
			textFieldClassif.setDocument(new FixedLengthDocument(8, '0', '9'));
			textFieldClassif.setHorizontalAlignment(0);
		}
		return textFieldClassif;
	}

	private void setFormMenosClassificacao(
			Classificacao classificacao) {
		if (classificacao != null) {
			getTextFieldDesc().setText(classificacao.getDescricao());
			getTextArea().setText(classificacao.getProdutoEnquadrado());
		}
	}
	public ClassificacaoActionsManager getAction() {
		if (action == null) {
			action = new ClassificacaoActionsManager();
		}
		return action;
	}

	public void setAction(ClassificacaoActionsManager action) {
		this.action = action;
	}

	public Classificacao getClassificacao() {
		return this.classificacao;
	}

	public void setClassificacao(Classificacao classificacao) {
		this.classificacao = classificacao;
	}

	public ArrayList<Classificacao> getClassificacaos() {
		if (classificacaos == null) {
			classificacaos = new ArrayList<Classificacao>();
		}
		return classificacaos;
	}

	public void setClassificacaos(ArrayList<Classificacao> classificacaos) {
		this.classificacaos = classificacaos;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("Produtos Enquadrados:");
			label.setBounds(22, 58, 209, 14);
		}
		return label;
	}
	private JScrollPane getScrollPane_1() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(22, 74, 418, 176);
			scrollPane.setViewportView(getTextArea());
		}
		return scrollPane;
	}
	private JTextArea getTextArea() {
		if (textArea == null) {
			textArea = new JTextArea();
			textArea.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					if (arg0.getKeyCode() == 40) {
						if (btnAlterar != null)
							getBtnAlterar().requestFocus();
						else
							getBtnSalvar().requestFocus();
					}
					if (arg0.getKeyCode() == 38) {
						getTextFieldDesc().requestFocus();
					}
				}
			});
		}
		return textArea;
	}
}
